﻿using OrBitDataModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Windows.Forms;
using OrBitDataModule.Base;
using System.Net.Sockets;
using System.Reflection.Emit;
using OrBitDataModule.Common;
using OrBitDataModule.Models;
using Newtonsoft.Json;
using System.Collections.Specialized;
using System.Net;
using Quartz.Util;
using System.Net.Http;

namespace OrBitDataModule.Common
{
    public static class WebApi
    {
        /// <summary>
        /// WebApi地址
        /// </summary>
        public static string BaseApiUri { get => GetBaseApiUri(); }

        private static string GetBaseApiUri()
        {
            string baseApiUrl = ConfigHelper.GetValue("BaseApiUri");
            if (!baseApiUrl.EndsWith("/"))
            {
                baseApiUrl += "/";
            }
            return baseApiUrl;
        }
        /// <summary>
        /// 登录接口，因为没有专用的验证帐号密码的接口，使用获取token接口，配置文件字段：LoginApiName
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static async Task<(bool Result, string Message)> Login(string userName, string password)
        {
            if (string.IsNullOrWhiteSpace(BaseApiUri))
            {
                return (false, "未设置WebApi地址");
            }

            try
            {
                using (var httpClient = new HttpClient())
                {
                    var formData = new Dictionary<string, string>
                    {
                        { "UserName", userName },
                        { "Password", password },
                        { "ApiName", ConfigHelper.GetValue("LoginApiName") }
                    };

                    HttpResponseMessage response = await httpClient.PostAsync($"{BaseApiUri}api/OrBitWebAPILogin", new FormUrlEncodedContent(formData));

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        var obj = JObject.Parse(responseBody);
                        bool result = obj["result"].Value<bool>();
                        string message = obj["msg"].Value<string>();

                        if (result)
                        {
                            SharedData.LoginUserName = userName;
                            SharedData.LoginUserPassword = password;
                        }
                        return (result, message);
                    }
                    else
                    {
                        return (false, "接口出错");
                    }
                }
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }


        /// <summary>
        /// 登录获取token
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static (bool Result, string Token, int Expiration, string Message) GetAccessToken(string apiName, string userName, string password)
        {
            if (string.IsNullOrWhiteSpace(BaseApiUri))
            {
                throw new Exception("未设置WebApi地址");
            }
            try
            {
                using (var httpClient = new HttpClient())
                {
                    var formData = new Dictionary<string, string>
                    {
                        { "UserName", userName },
                        { "Password", password },
                        { "ApiName", apiName }
                    };

                    HttpResponseMessage response = httpClient.PostAsync($"{BaseApiUri}/api/OrBitWebAPILogin", new FormUrlEncodedContent(formData)).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = response.Content.ReadAsStringAsync().Result;
                        var obj = JObject.Parse(responseBody);
                        bool result = obj["result"].Value<bool>();
                        string token = obj["token"].Value<string>();
                        int expiration = obj["expiration"].Value<int>();
                        string message = obj["msg"].Value<string>();

                        return (result, token, expiration, message);
                    }
                    else
                    {
                        return (false, "", 0, "接口出错");
                    }
                }
            }
            catch (Exception ex)
            {
                return (false, "", 0, ex.Message);
            }
        }

        /// <summary>
        /// 登录获取token
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<(bool Result, string Token, int Expiration, string Message)> GetAccessTokenAsync(string apiName, string userName, string password)
        {
            if (string.IsNullOrWhiteSpace(BaseApiUri))
            {
                throw new Exception("未设置WebApi地址");
            }

            try
            {
                using (var httpClient = new HttpClient())
                {
                    var formData = new Dictionary<string, string>
                {
                    { "UserName", userName },
                    { "Password", password },
                    { "ApiName", apiName }
                };

                    HttpResponseMessage response = await httpClient.PostAsync($"{BaseApiUri}/api/OrBitWebAPILogin", new FormUrlEncodedContent(formData));

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        var obj = JObject.Parse(responseBody);
                        bool result = obj["result"].Value<bool>();
                        string token = obj["token"].Value<string>();
                        int expiration = obj["expiration"].Value<int>();
                        string message = obj["msg"].Value<string>();

                        return (result, token, expiration, message);
                    }
                    else
                    {
                        return (false, "", 0, "接口出错");
                    }
                }
            }
            catch (Exception ex)
            {
                return (false, "", 0, ex.Message);
            }
        }
        public static async Task<(bool Result, string Response)> HttpPostAsync(string apiName, string token, object obj)
        {
            if (string.IsNullOrWhiteSpace(BaseApiUri))
            {
                return (false, "未设置WebApi地址");
            }

            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add("token", token);
                    Dictionary<string, string> formData = ToFormData(obj);
                    var response = await httpClient.PostAsync($"{BaseApiUri}/api/OrBitWebAPI?ApiName={apiName}", new FormUrlEncodedContent(formData));
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        return (true, responseBody);
                    }
                    else
                    {
                        return (false, "接口出错");
                    }
                }
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }

        public static (bool Result, string Response) HttpPost(string apiName, string token, object obj)
        {
            if (string.IsNullOrWhiteSpace(BaseApiUri))
            {
                return (false, "未设置WebApi地址");
            }
            try
            {
                using (var httpClient = new HttpClient())
                {
                    Dictionary<string, string> formData = ToFormData(obj);
                    httpClient.DefaultRequestHeaders.Add("token", token);
                    var response = httpClient.PostAsync($"{BaseApiUri}/api/OrBitWebAPI?ApiName={apiName}", new FormUrlEncodedContent(formData)).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = response.Content.ReadAsStringAsync().Result;
                        return (true, responseBody);
                    }
                    else
                    {
                        return (false, "接口出错");
                    }
                }
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }
        /// <summary>
        /// 设备接口提交，inputRequest转base64，绕过接口的安全检查
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="token"></param>
        /// <param name="inputParameter"></param>
        /// <param name="inputRequest"></param>
        /// <returns></returns>
        public static async Task<DeviceIntegration> IntegrationApiPostAsync(string apiName, string token, InputParameter inputParameter, string inputRequest)
        {
            if (string.IsNullOrWhiteSpace(BaseApiUri))
            {
                return new DeviceIntegration() { Result = false, ReturnMessage = "未设置WebApi地址", OutputResponse = string.Empty };
            }
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add("token", token);
                    Dictionary<string, string> formData = ToFormData(new { InputParameter = JsonConvert.SerializeObject(inputParameter), InputRequest = StringUtils.StringToBase64(inputRequest) });
                    var response = await httpClient.PostAsync($"{BaseApiUri}/api/OrBitDeviceIntegrationApi?ApiName={apiName}", new FormUrlEncodedContent(formData));
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        return JsonConvert.DeserializeObject<DeviceIntegration>(responseBody);
                    }
                    else
                    {
                        return new DeviceIntegration() { Result = false, ReturnMessage = "接口出错", OutputResponse = string.Empty };
                    }
                }
            }
            catch (Exception ex)
            {
                return new DeviceIntegration() { Result = false, ReturnMessage = ex.Message, OutputResponse = string.Empty };
            }
        }

        public static DeviceIntegration IntegratioApiPost(string apiName, string token, string inputParameter, string inputRequest)
        {
            if (string.IsNullOrWhiteSpace(BaseApiUri))
            {
                return new DeviceIntegration() { Result = false, ReturnMessage = "未设置WebApi地址", OutputResponse = string.Empty };
            }
            try
            {
                using (var httpClient = new HttpClient())
                {
                    Dictionary<string, string> formData = ToFormData(new { InputParameter = JsonConvert.SerializeObject(inputParameter), InputRequest = inputRequest });
                    httpClient.DefaultRequestHeaders.Add("token", token);
                    var response = httpClient.PostAsync($"{BaseApiUri}/api/OrBitDeviceIntegrationApi?ApiName={apiName}", new FormUrlEncodedContent(formData)).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = response.Content.ReadAsStringAsync().Result;
                        return JsonConvert.DeserializeObject<DeviceIntegration>(responseBody);
                    }
                    else
                    {
                        return new DeviceIntegration() { Result = false, ReturnMessage = "接口出错", OutputResponse = string.Empty };
                    }
                }
            }
            catch (Exception ex)
            {
                return new DeviceIntegration() { Result = false, ReturnMessage = ex.Message, OutputResponse = string.Empty };
            }
        }

        private static Dictionary<string, string> ToFormData(object postData)
        {
            var properties = postData.GetType().GetProperties();
            Dictionary<string, string> dic = new Dictionary<string, string>();

            foreach (var property in properties)
            {
                dic.Add(property.Name, property.GetValue(postData)?.ToString() ?? "");
            }
            return dic;
        }
    }
}

